<?php
namespace app\common\model\food;

use think\facade\Db;

/**
 * 发券记录模型
 */
class CouponLog extends BaseModel
{
    // 定义表名
    protected $name = 'food_coupon_log';

    // 定义主键
    protected $pk = 'coupon_log_id';

    // 追加字段
    protected $append = [];

    /**
     * 关联用户表
     */
    public function user()
    {
        return $this->belongsTo('app\\common\\model\\food\\User','user_id');
    }

    /**
     * 关联门店表
     */
    public function shop()
    {
        return $this->belongsTo('app\\common\\model\\food\\Shop','shop_id');
    }

    /**
     * 关联优惠券表
     */
    public function coupon()
    {
        return $this->belongsTo('app\\common\\model\\food\\Coupon','coupon_id');
    }
    
    /**
     * 等级
     */
    public function getVAttr($value)
    {
        $status = ['全部会员','V1','V2','V3','V4','V5','V6'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 获取列表
     */
    public function getList()
    {
        // 排序规则
        $sort = [];
        $sort = ['coupon_log_id' => 'desc'];//按照时间排序
        // 执行查询
        return $this->with(['shop','coupon','user'])
            ->order($sort)
            ->paginate(['list_rows'=>15,'query' => request()->param()]);
    }

    /**
     * 添加
     */
    public function add(array $data,$user_id = 0)
    {
        $data['user_id'] = $user_id;
        $data['applet_id'] = self::$applet_id;
        //获取优惠券详情
        $coupon = Coupon::get($data['coupon_id']);
        //获取合法用户的id
        $filter = [];
        $data['v'] > 0 && $filter['v'] = $data['v'];
        $userId = User::where($filter)->order('user_id','desc')->column('user_id');
        //计算发送数量
        $data['count'] = count($userId);
        //计算优惠券到期时间
        switch ($coupon['valid_time']['value']) {
            case '10':
                $expiretime = strtotime(date('Y-m-d').'23:59:59');
                break;
            case '20':
                $expiretime = strtotime("+1 week");
                break;
            case '30':
                $expiretime = strtotime("+1 month");
                break;
            case '40':
                $expiretime = strtotime("+1 year");
                break;
            default:
                $expiretime = time();
                break;
        }
        //组成用户批量记录
        $userCoupon = array();
        foreach ($userId as $key => $value) {
            array_push($userCoupon,[
                'coupon_id' => $data['coupon_id'],
                'type' => $coupon['type']['value'],
                'rule' => $coupon['rule']['value'],
                'user_id' => $value,
                'shop_id' => $data['shop_id'],
                'applet_id' => self::$applet_id,
                'expiretime' => $expiretime
            ]);
        }
        // 开启事务
        Db::startTrans();
        try {
            // 添加记录
            $this->save($data);
            // 用户发券
            if(sizeof($userCoupon) > 0){
                $couponUser = new CouponUser;
                $couponUser->saveAll($userCoupon);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;  
    }

    /**
     * 删除
     */
    public function remove()
    {
        //验证是否有未使用
        
        return $this->delete(); 
    }
}
